#include <jni.h>
#include <stdio.h>
#include <cstdlib>
#include <stdio.h>
#include <windows.h> 
#include <iostream>
#include <string>

#include "aSSVAPI.h"
#include "SSV_5_40/win32def.h"
#include "SSV_5_40/ssv.h"

/**
 *
 * @author hanhnv
 */

JNIEXPORT jstring JNICALL Java_visiodent_aSSVAPI_sisLireCartePS
  (JNIEnv *env, jobject obj, jstring NomRessourcePS, jstring NomRessourceLecteur, jstring CodePorteurPS)
{
    jstring result = NULL;
    
    // create an instance to load DLL
    HINSTANCE LoadGIE;
    LoadGIE = LoadLibrary("C:\\Working\\SesamVitale\\Source\\Technique\\Application\\VisioDentNative\\SSV_5_40\\ssvw32.dll");
    
    if ((UINT)LoadGIE <= 32 )
        return result; // load dll failed
    
    // load Lib
    SSV_InitLIB2 ssv_InitLib = 0;
    // get adress for function ssv_initlib2    
    ssv_InitLib = (SSV_InitLIB2)GetProcAddress(LoadGIE, "SSV_InitLIB2");
    
    if (!ssv_InitLib)
        return result; // getProcAdress for initLib failed
    
    const char* szSesamPath = "C:\\Program Files (x86)\\santesocial\\fsv\\1.40.9\\conf\\sesam.ini";
    unsigned short usLib = ssv_InitLib(szSesamPath);
    
    if (usLib != 0)
        return result; // invoke initLib2 function failed
        
    // set pointer function
    SSV_LireCartePS  ssv_LireCartePS = 0;    
    void* pBufferOutPS =  NULL;
    unsigned int pSize = 0;
    // create native string to avoid crash the JVM.
    const char* nativeNomRessourcePS = (env)->GetStringUTFChars(NomRessourcePS, 0); 
    const char* nativeNomRessourceLecteur = (env)->GetStringUTFChars(NomRessourceLecteur, 0);
    const char* nativeCodePorteurPS = (env)->GetStringUTFChars(CodePorteurPS, 0);
    
    unsigned short usLirePS = ssv_LireCartePS(nativeNomRessourcePS, nativeNomRessourceLecteur, nativeCodePorteurPS, &pBufferOutPS, &pSize);
    if (usLirePS != 0)
        return result; // failed invoke LireCartePS
    char* pBufferPS = (char*)pBufferOutPS;
    // copy Buffer to jstring
    result = (env)->NewStringUTF(pBufferPS);    

    // release string 
    (env)->ReleaseStringUTFChars(NomRessourcePS, nativeNomRessourcePS);
    (env)->ReleaseStringUTFChars(NomRessourceLecteur, nativeNomRessourceLecteur);
    (env)->ReleaseStringUTFChars(CodePorteurPS, nativeCodePorteurPS);
    
    return result;    
}
